<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>推箱子小游戏</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #f0f0f0;
            min-height: 100vh;
            padding: 20px;
        }
        
        h1 {
            color: #333;
            margin-bottom: 20px;
            font-size: 28px;
        }
        
        .game-container {
            display: flex;
            flex-direction: column;
            align-items: center;
            background-color: #fff;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }
        
        .game-info {
            display: flex;
            justify-content: space-between;
            width: 100%;
            max-width: 400px;
            margin-bottom: 20px;
            font-size: 18px;
            color: #555;
        }
        
        .game-board {
            display: grid;
            gap: 2px;
            background-color: #ddd;
            padding: 10px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .cell {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            background-color: #fff;
            border-radius: 4px;
            transition: background-color 0.2s;
        }
        
        .wall { background-color: #666; }
        .box { background-color: #f39c12; }
        .target { background-color: #27ae60; }
        .box-on-target { background-color: #e74c3c; }
        .player { background-color: #3498db; }
        .player-on-target { background-color: #9b59b6; }
        
        .controls {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 10px;
            margin-top: 20px;
        }
        
        .control-buttons {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 5px;
            width: 200px;
        }
        
        .btn {
            padding: 10px 15px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: background-color 0.2s;
        }
        
        .btn:hover { background-color: #2980b9; }
        .btn:active { transform: scale(0.95); }
        
        .btn-secondary { background-color: #95a5a6; }
        .btn-secondary:hover { background-color: #7f8c8d; }
        
        .message {
            margin-top: 15px;
            font-size: 18px;
            color: #e74c3c;
            font-weight: bold;
            height: 24px;
        }
        
        @media (max-width: 480px) {
            .cell { width: 30px; height: 30px; font-size: 20px; }
            .game-info { font-size: 16px; }
        }
    </style>
</head>
<body>
    <h1>推箱子小游戏</h1>
    <div class="game-container">
        <div class="game-info">
            <div>步数: <span id="steps">0</span></div>
            <div>关卡: <span id="level">1</span>/<span id="total-levels">5</span></div>
        </div>
        <div id="game-board" class="game-board"></div>
        <div class="message" id="message"></div>
        <div class="controls">
            <div class="control-buttons">
                <div></div>
                <button class="btn" onclick="movePlayer(0, -1)">↑</button>
                <div></div>
                <button class="btn" onclick="movePlayer(-1, 0)">←</button>
                <div></div>
                <button class="btn" onclick="movePlayer(1, 0)">→</button>
                <div></div>
                <button class="btn" onclick="movePlayer(0, 1)">↓</button>
                <div></div>
            </div>
            <button class="btn btn-secondary" onclick="restartLevel()">重新开始</button>
            <button class="btn btn-secondary" onclick="nextLevel()">下一关</button>
        </div>
    </div>

    <script>
        // 游戏常量
        const WALL = '#';
        const EMPTY = ' ';
        const TARGET = '.';
        
        // 游戏状态
        let currentLevel = 0;
        let steps = 0;
        let gameMap = [];
        let playerPos = { x: 0, y: 0 };
        let boxes = [];
        let targets = [];
        let originalLevels = [];
        
        // 游戏关卡数据 - 确保所有关卡都可解
        const levels = [
            {
                // 第一关：非常简单，确保可以通关
                map: [
                    ['#', '#', '#', '#', '#', '#'],
                    ['#', ' ', ' ', ' ', ' ', '#'],
                    ['#', ' ', ' ', ' ', ' ', '#'],
                    ['#', ' ', '.', '.', ' ', '#'],
                    ['#', '#', '#', '#', '#', '#']
                ],
                player: {x: 2, y: 1},
                boxes: [{x: 2, y: 2}, {x: 3, y: 2}],
                targets: [{x: 2, y: 3}, {x: 3, y: 3}]
            },
            {
                // 第二关：简单挑战（重新设计确保可通关）
                map: [
                    ['#', '#', '#', '#', '#'],
                    ['#', '.', ' ', ' ', '#'],
                    ['#', ' ', ' ', ' ', '#'],
                    ['#', ' ', ' ', ' ', '#'],
                    ['#', '#', '#', '#', '#']
                ],
                player: {x: 3, y: 2},
                boxes: [{x: 2, y: 2}],
                targets: [{x: 1, y: 1}]
            },
            {
                // 第三关：基础难度（调整为两个箱子与目标点匹配）
                map: [
                    ['#', '#', '#', '#', '#', '#'],
                    ['#', '.', ' ', ' ', '#', '#'],
                    ['#', '.', ' ', ' ', ' ', '#'],
                    ['#', '#', ' ', ' ', ' ', '#'],
                    ['#', ' ', ' ', ' ', '#', '#'],
                    ['#', '#', '#', '#', '#', '#']
                ],
                player: {x: 3, y: 3},
                boxes: [{x: 2, y: 2}, {x: 3, y: 2}],
                targets: [{x: 1, y: 1}, {x: 1, y: 2}]
            },
            {
                // 第四关：简化设计确保可通关
                map: [
                    ['#', '#', '#', '#', '#'],
                    ['#', '.', '.', ' ', '#'],
                    ['#', ' ', ' ', ' ', '#'],
                    ['#', ' ', ' ', ' ', '#'],
                    ['#', '#', '#', '#', '#']
                ],
                player: {x: 3, y: 2},
                boxes: [{x: 2, y: 2}],
                targets: [{x: 1, y: 1}]
            },
            {
                // 第五关：基础难度确保可通关
                map: [
                    ['#', '#', '#', '#', '#', '#', '#'],
                    ['#', '.', '.', '.', ' ', ' ', '#'],
                    ['#', ' ', ' ', ' ', ' ', ' ', '#'],
                    ['#', ' ', ' ', ' ', ' ', ' ', '#'],
                    ['#', ' ', ' ', ' ', ' ', ' ', '#'],
                    ['#', '#', '#', '#', '#', '#', '#']
                ],
                player: {x: 4, y: 3},
                boxes: [{x: 2, y: 3}, {x: 3, y: 3}, {x: 4, y: 3}],
                targets: [{x: 1, y: 1}, {x: 2, y: 1}, {x: 3, y: 1}]
            }
        ];
        
        // 初始化游戏
        function initGame() {
            // 保存原始关卡数据
            saveOriginalLevels();
            // 加载第一关
            loadLevel(0);
        }
        
        // 保存原始关卡数据
        function saveOriginalLevels() {
            originalLevels = JSON.parse(JSON.stringify(levels));
        }
        
        // 加载关卡
        function loadLevel(levelIndex) {
            if (levelIndex >= levels.length) {
                document.getElementById('message').textContent = '恭喜你通关了所有关卡！';
                return;
            }
            
            // 重置当前关卡数据
            const levelData = JSON.parse(JSON.stringify(originalLevels[levelIndex]));
            
            // 更新游戏状态
            currentLevel = levelIndex;
            gameMap = levelData.map;
            playerPos = { ...levelData.player };
            boxes = JSON.parse(JSON.stringify(levelData.boxes));
            targets = JSON.parse(JSON.stringify(levelData.targets));
            steps = 0;
            
            // 更新UI显示
            document.getElementById('steps').textContent = steps;
            document.getElementById('level').textContent = levelIndex + 1;
            document.getElementById('total-levels').textContent = levels.length;
            document.getElementById('message').textContent = '';
            
            // 渲染地图
            renderMap();
        }
        
        // 渲染地图
        function renderMap() {
            const board = document.getElementById('game-board');
            board.innerHTML = '';
            
            // 设置网格大小
            board.style.gridTemplateColumns = `repeat(${gameMap[0].length}, 1fr)`;
            
            // 遍历地图创建单元格
            for (let y = 0; y < gameMap.length; y++) {
                for (let x = 0; x < gameMap[y].length; x++) {
                    const cell = document.createElement('div');
                    cell.classList.add('cell');
                    
                    // 检查单元格类型
                    const isWall = gameMap[y][x] === WALL;
                    const isPlayer = playerPos.x === x && playerPos.y === y;
                    const hasBox = boxes.some(box => box.x === x && box.y === y);
                    const isTarget = targets.some(target => target.x === x && target.y === y);
                    
                    // 设置单元格样式和内容
                    if (isWall) {
                        cell.classList.add('wall');
                        cell.textContent = '🧱';
                    } else if (isPlayer && hasBox) {
                        // 不应该发生，因为推动机制会避免这种情况
                        cell.classList.add('player');
                        cell.textContent = '😀';
                    } else if (isPlayer && isTarget) {
                        cell.classList.add('player-on-target');
                        cell.textContent = '😀';
                    } else if (isPlayer) {
                        cell.classList.add('player');
                        cell.textContent = '😀';
                    } else if (hasBox && isTarget) {
                        cell.classList.add('box-on-target');
                        cell.textContent = '📦';
                    } else if (hasBox) {
                        cell.classList.add('box');
                        cell.textContent = '📦';
                    } else if (isTarget) {
                        cell.classList.add('target');
                        cell.textContent = '🎯';
                    }
                    
                    board.appendChild(cell);
                }
            }
            
            // 检查是否完成关卡
            checkWin();
        }
        
        // 移动玩家
        function movePlayer(dx, dy) {
            const newX = playerPos.x + dx;
            const newY = playerPos.y + dy;
            
            // 检查是否是墙
            if (gameMap[newY][newX] === WALL) {
                return;
            }
            
            // 检查是否有箱子
            const boxIndex = boxes.findIndex(box => box.x === newX && box.y === newY);
            
            if (boxIndex !== -1) {
                // 尝试推动箱子
                const boxNewX = newX + dx;
                const boxNewY = newY + dy;
                
                // 检查箱子新位置是否是墙
                if (gameMap[boxNewY][boxNewX] === WALL) {
                    return;
                }
                
                // 检查箱子新位置是否有其他箱子
                const hasOtherBox = boxes.some((box, index) => 
                    index !== boxIndex && box.x === boxNewX && box.y === boxNewY
                );
                
                if (hasOtherBox) {
                    return;
                }
                
                // 推动箱子
                boxes[boxIndex].x = boxNewX;
                boxes[boxIndex].y = boxNewY;
            }
            
            // 移动玩家
            playerPos.x = newX;
            playerPos.y = newY;
            steps++;
            document.getElementById('steps').textContent = steps;
            
            // 重新渲染
            renderMap();
        }
        
        // 检查是否获胜 - 更严格的胜利条件检查
        function checkWin() {
            // 确保箱子数量和目标点数量相等
            if (boxes.length !== targets.length || boxes.length === 0) {
                return;
            }
            
            // 检查每个箱子都在某个目标点上
            const allBoxesOnTargets = boxes.every(box => {
                return targets.some(target => target.x === box.x && target.y === box.y);
            });
            
            // 检查每个目标点都有箱子
            const allTargetsHaveBoxes = targets.every(target => {
                return boxes.some(box => box.x === target.x && box.y === target.y);
            });
            
            if (allBoxesOnTargets && allTargetsHaveBoxes) {
                document.getElementById('message').textContent = '恭喜你完成关卡！';
            }
        }
        
        // 重新开始当前关卡
        function restartLevel() {
            loadLevel(currentLevel);
        }
        
        // 下一关
        function nextLevel() {
            // 先检查当前关卡是否完成
            const allBoxesOnTargets = boxes.every(box => {
                return targets.some(target => target.x === box.x && target.y === box.y);
            });
            
            const allTargetsHaveBoxes = targets.every(target => {
                return boxes.some(box => box.x === target.x && box.y === target.y);
            });
            
            if (allBoxesOnTargets && allTargetsHaveBoxes) {
                loadLevel(currentLevel + 1);
            } else {
                document.getElementById('message').textContent = '请先完成当前关卡！';
            }
        }
        
        // 键盘控制
        document.addEventListener('keydown', (e) => {
            switch (e.key) {
                case 'ArrowUp':
                    e.preventDefault();
                    movePlayer(0, -1);
                    break;
                case 'ArrowDown':
                    e.preventDefault();
                    movePlayer(0, 1);
                    break;
                case 'ArrowLeft':
                    e.preventDefault();
                    movePlayer(-1, 0);
                    break;
                case 'ArrowRight':
                    e.preventDefault();
                    movePlayer(1, 0);
                    break;
                case 'r':
                case 'R':
                    restartLevel();
                    break;
                case 'n':
                case 'N':
                    nextLevel();
                    break;
            }
        });
        
        // 触摸控制
        let touchStartX = 0;
        let touchStartY = 0;
        
        document.addEventListener('touchstart', (e) => {
            touchStartX = e.touches[0].clientX;
            touchStartY = e.touches[0].clientY;
        });
        
        document.addEventListener('touchend', (e) => {
            if (!touchStartX || !touchStartY) return;
            
            const touchEndX = e.changedTouches[0].clientX;
            const touchEndY = e.changedTouches[0].clientY;
            
            const diffX = touchStartX - touchEndX;
            const diffY = touchStartY - touchEndY;
            
            // 判断滑动方向
            if (Math.abs(diffX) > Math.abs(diffY)) {
                if (Math.abs(diffX) > 50) { // 需要一定的滑动距离
                    movePlayer(diffX > 0 ? -1 : 1, 0);
                }
            } else {
                if (Math.abs(diffY) > 50) {
                    movePlayer(0, diffY > 0 ? -1 : 1);
                }
            }
            
            touchStartX = 0;
            touchStartY = 0;
        });
        
        // 页面加载完成后初始化游戏
        window.addEventListener('DOMContentLoaded', initGame);
    </script>
</body>
</html>